/** 
 * ButtonBuilder,Build auth. buttons in grids or other containers to loging user.
 * @version: 1.0.2
 */

/**
 * @param {Object} owner,grid or win.
 * @param {Number} resourceId
 * @param {Number} ownerType
 */
ButtonBuilder = function(owner,resourceId,ownerType){
	this.buttons = [];
	this.owner = owner;
	this.resourceId = resourceId;
	this.ownerType = ownerType;
};

//prototype
ButtonBuilder.prototype = {
    /**
     * Build and/or add buttons to bar if defined.
     * @param {Object} bar (optional),tbar or bbar,if is defined,buttons will be add to it.
	 * @param {Object} yourButtons (optional),self-defined buttons.
	 * @param {integer} offSet (optional),yourButtons' position to insert.
     */
    build : function(bar){
	    this.load(bar);
    },

	/**
	 * Get button array.
	 */
    getButtons : function(){
    	return this.buttons;
    },
    
    //private
    load : function(bar){
    	var bd = this;
		Ext.Ajax.request({
	        url: 'loadActions.jhtml',
	        method:'POST',
	        params:{moduleId:bd.resourceId, ownertype:bd.ownerType},
	        success:function(response){
	        	bd.createButtons(Ext.util.JSON.decode(response.responseText));
			    if(bar){
		        	bar.removeAll(true);
		        	bar.add(bd.buttons);
			        bar.doLayout();
			    }
	        },
	        failure:function(response){
	           // msgBox.alert($('jbob.common.fail'), $('jbob.common.errors.access'));
	        }
	    });
    },
     
    //private
	createButtons : function(buttonArr){
    	var button,initalConfig;
	    for(var i=0;i<buttonArr.length;i=i+1){
	    	button = buttonArr[i];
	    	this.splitBtnHandler(button); 
            initalConfig = {
            		name: button.enname,
	                text: button.name,
	                iconCls: button.icon,
	                tooltip: button.tooltip,
	                handler: button.method
	        };

            if(this.config) initalConfig = Ext.apply(initalConfig, this.config);
	    	this.buttons.push([initalConfig,'-']);
	   }
    },
    
    //private
    //Handle with button.method
    splitBtnHandler : function(button){
    	var handler = button.handler;
    	if(!handler || handler=='' || handler=='null') return;
    	button.method = this.owner[handler];
    }
};